﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KZ.Express.H.Presenter;
using KZ.Express.H.ENT;
using KZ.Utilities;
using KZ.Express.H.CustomControl;

namespace KZ.Express.H.Orders
{
    public partial class AccountOrderListView : BaseView, IOrderListView
    {
        #region Fields

        object _preValue;
        List<DataRow> _changedRow;
        AutoCompleteStringCollection _customerAutoComplete, _countryAutoComplete,
            _carrierAutoComplete, _supplierAutoComplete, _saleAutoComplete;

        #endregion

        #region Private Methods

        private void AccountOrderListView_Load(object sender, EventArgs e)
        {
            _changedRow = new List<DataRow>();
            _customerAutoComplete = new AutoCompleteStringCollection();
            _countryAutoComplete = new AutoCompleteStringCollection();
            _carrierAutoComplete = new AutoCompleteStringCollection();
            _supplierAutoComplete = new AutoCompleteStringCollection();
            _saleAutoComplete = new AutoCompleteStringCollection();

            this.dtpFrom.Value = DateTime.Today.AddDays(-7);
            this.dtpTo.Value = DateTime.Today;
            this.toolTip1.SetToolTip(this.txtWeight, ">={Số ký}\n>{Số ký}\n<={Số ký}\n<{Số ký}\n{Từ số ký}-{Đến số ký}");

            LoadCountry();
            LoadCustomer();
            LoadSale();
            LoadCarrier();
            LoadSupplier();
        }

        protected override void View_OnDeleteClick<T>(object sender, EventArgs e)
        {
            try
            {
                if (ShowMessageBoxConfirm("Bạn có chắc chắn muốn xóa dữ liệu?") == DialogResult.Yes)
                {
                    _presenter.Delete<T>(GetSelecteds());
                    _changedRow.Clear();
                }
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void dtgOrder_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is TextBox)
            {
                TextBox txt = e.Control as TextBox;
                if (dtgOrder.CurrentCell.ColumnIndex == colCustomerName.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = _customerAutoComplete;
                }
                else if (dtgOrder.CurrentCell.ColumnIndex == colCountryName.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = _countryAutoComplete;
                }
                else if (dtgOrder.CurrentCell.ColumnIndex == colType.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = new AutoCompleteStringCollection();
                    txt.AutoCompleteCustomSource.AddRange(new string[] { "DOX", "PACK" });
                }
                else if (dtgOrder.CurrentCell.ColumnIndex == colCarrierName.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = _carrierAutoComplete;
                }
                else if (dtgOrder.CurrentCell.ColumnIndex == colSupplierName.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = _supplierAutoComplete;
                }
                else if (dtgOrder.CurrentCell.ColumnIndex == colSaleName.Index)
                {
                    txt.Multiline = false;
                    txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
                    txt.AutoCompleteCustomSource = _saleAutoComplete;
                }
            }
        }

        private void dtgOrder_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _preValue = dtgOrder[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dtgOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (_preValue == dtgOrder[e.ColumnIndex, e.RowIndex].Value)
                    return;

                if ((e.ColumnIndex == colListPrice.Index || e.ColumnIndex == colFuel.Index || e.ColumnIndex == colVAT.Index) &&
                  Utility.DecimalNParse(_preValue) == Utility.DecimalNParse(dtgOrder[e.ColumnIndex, e.RowIndex].Value))
                    return;

                if (e.ColumnIndex == colOrderDate.Index &&
                    Utility.DateTimeParse(_preValue) == Utility.DateTimeParse(dtgOrder[e.ColumnIndex, e.RowIndex].Value))
                    return;

                AccountOrderPresenter presenter = _presenter as AccountOrderPresenter;

                if (e.ColumnIndex == colCustomerName.Index)
                    presenter.UpdateCustomer();
                else if (e.ColumnIndex == colCountryName.Index)
                    presenter.UpdateCountry();
                else if (e.ColumnIndex == colType.Index)
                {
                    string value = Utility.StringParse(dtgOrder[colType.Index, e.RowIndex].Value);
                    switch (value.ToLower())
                    {
                        case "dox":
                        case "pack":
                            dtgOrder[colType.Index, e.RowIndex].Value = value.ToUpper();
                            break;
                        default:
                            dtgOrder[colType.Index, e.RowIndex].Value = DBNull.Value;
                            throw new BusinessLogicException("Loại bill không đúng, chỉ được là 'DOX' hoặc 'PACK'");
                    }
                }
                else if (e.ColumnIndex == colCarrierName.Index)
                    presenter.UpdateCarrier();
                else if (e.ColumnIndex == colSupplierName.Index)
                    presenter.UpdateSupplier();
                else if (e.ColumnIndex == colSaleName.Index)
                    presenter.UpdateSale();
                else if (e.ColumnIndex == colListPrice.Index)
                    presenter.UpdateListPrice();
                else if (e.ColumnIndex == colFuel.Index)
                    presenter.UpdateFuel();
                else if (e.ColumnIndex == colVAT.Index)
                    presenter.UpdateVAT();

                presenter.AddChangedRow();
            }
            catch (Exception ex)
            {
                ShowMessageBoxError(ex.Message);
            }
            finally
            {
                dtgOrder.Refresh();
            }
        }

        private void dtgOrder_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.ColumnIndex == colCustomerID.Index || e.ColumnIndex == colCountryID.Index ||
                e.ColumnIndex == colCarrierID.Index || e.ColumnIndex == colSupplierID.Index ||
                e.ColumnIndex == colSaleID.Index)
                dtgOrder[e.ColumnIndex, e.RowIndex].Value = DBNull.Value;
            else if (e.ColumnIndex != -1 && e.RowIndex != -1)
            {
                if (_preValue == null || Convert.IsDBNull(_preValue))
                    dtgOrder[e.ColumnIndex, e.RowIndex].Value = DBNull.Value;
                else
                    dtgOrder[e.ColumnIndex, e.RowIndex].Value = _preValue;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _changedRow.Clear();
            string weight = this.txtWeight.Text.Trim();
            if (String.IsNullOrWhiteSpace(weight))
            {
                this.FromWeight = null;
                this.ToWeight = null;
            }
            else
            {
                if (weight.StartsWith(">="))
                {
                    this.FromWeight = Utility.DecimalParse(weight.Replace(">=", String.Empty).Trim());
                    this.ToWeight = 9999;
                }
                else if (weight.StartsWith(">"))
                {
                    this.FromWeight = Utility.DecimalParse(weight.Replace(">", String.Empty).Trim()) + 0.1M;
                    this.ToWeight = 9999;
                }
                else if (weight.StartsWith("<="))
                {
                    this.ToWeight = Utility.DecimalParse(weight.Replace("<=", String.Empty).Trim());
                    this.FromWeight = 0;
                }
                else if (weight.StartsWith("<"))
                {
                    this.ToWeight = Utility.DecimalParse(weight.Replace("<", String.Empty).Trim()) - 0.1M;
                    this.FromWeight = 0;
                }
                else if (weight.Split('-').Length == 2)
                {
                    string[] tmp = weight.Split('-');
                    this.FromWeight = Utility.DecimalNParse(tmp[0].Trim());
                    this.ToWeight = Utility.DecimalNParse(tmp[1].Trim());
                }
                else
                    this.FromWeight = this.ToWeight = Utility.DecimalNParse(weight);
            }
            LoadData<AccountOrderENT>();
        }

        private void btnViewAll_Click(object sender, EventArgs e)
        {
            _changedRow.Clear();
            this.Search = null;
            this.FromWeight = null;
            this.ToWeight = null;
            this.txtWeight.Clear();
            LoadData<AccountOrderENT>();
        }

        private void LoadCountry()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<CountryENT>(null);
                foreach (DataRow row in dt.Rows)
                    _countryAutoComplete.Add(Utility.StringParse(row["CountryName"]));
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbCountryID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadCustomer()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<CustomerENT>(null);
                foreach (DataRow row in dt.Rows)
                    _customerAutoComplete.Add(Utility.StringParse(row["CustomerName"]));
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadCarrier()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<CarrierENT>(null);
                foreach (DataRow row in dt.Rows)
                    _carrierAutoComplete.Add(Utility.StringParse(row["CarrierName"]));
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbCarrierID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadSupplier()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<SupplierENT>(null);
                foreach (DataRow row in dt.Rows)
                    _supplierAutoComplete.Add(Utility.StringParse(row["SupplierName"]));
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbSupplierID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadSale()
        {
            try
            {
                SearchCriteria search = new SearchCriteria();
                search.Add("RoleID", 2);
                DataTable dt = _presenter.LoadDataTable<UserENT>(search);
                foreach (DataRow row in dt.Rows)
                    _saleAutoComplete.Add(Utility.StringParse(row["FullName"]));
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbSaleID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        #endregion

        #region Constructors

        public AccountOrderListView()
        {
            InitializeComponent();
            Initialize(this.dtgOrder);

            _presenter = new AccountOrderPresenter(this);

            this.ObjectID = (int)Objects.CSOrder;
            this.ActionName = "ListWithSaveExportFuel";
            this.VisibleChanged += new EventHandler(View_VisibleChanged<AccountOrderENT>);
            this.dtgOrder.Sorted += new EventHandler(Datagrid_Sorted);
            this.OnDeleteClick += new DeleteClickHandler(View_OnDeleteClick<AccountOrderENT>);

            Global.SetDoubleBuffered(dtgOrder);
        }

        #endregion

        #region Public Properties

        public int OrderID
        {
            get { return Utility.IntParse(dtgOrder[colOrderID.Index, dtgOrder.CurrentCell.RowIndex].Value); }
        }

        [Search]
        public DateTime From
        {
            get { return dtpFrom.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpFrom.Value = value;
            }
        }

        [Search]
        public DateTime To
        {
            get { return dtpTo.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpTo.Value = value;
            }
        }

        [Search]
        public string CustomerName
        {
            get { return txtCustomerName.Text.Trim(); }
            set { txtCustomerName.Text = value; }
        }

        [Search]
        public decimal? FromWeight { get; set; }

        [Search]
        public decimal? ToWeight { get; set; }

        [Search]
        public int? CountryID
        {
            get { return Utility.IntNParse(cmbCountryID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbCountryID.SelectedValue = value;
                else
                    cmbCountryID.SelectedValue = DBNull.Value;
            }
        }

        [Search]
        public int? SaleID
        {
            get { return Utility.IntNParse(cmbSaleID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbSaleID.SelectedValue = value;
                else
                    cmbSaleID.SelectedValue = DBNull.Value;
            }
        }

        [Search]
        public string OrderNumber
        {
            get { return txtOrderNumber.Text.Trim(); }
            set { txtOrderNumber.Text = value; }
        }

        [Search]
        public string MasterOrderNumber
        {
            get { return txtMasterOrderNumber.Text.Trim(); }
            set { txtMasterOrderNumber.Text = value; }
        }

        [Search]
        public int? CarrierID
        {
            get { return Utility.IntNParse(cmbCarrierID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbCarrierID.SelectedValue = value;
                else
                    cmbCarrierID.SelectedValue = DBNull.Value;
            }
        }

        [Search]
        public int? SupplierID
        {
            get { return Utility.IntNParse(cmbSupplierID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbSupplierID.SelectedValue = value;
                else
                    cmbSupplierID.SelectedValue = DBNull.Value;
            }
        }

        public List<DataRow> ChangedRows
        {
            get { return _changedRow; }
        }

        public override DataTable Table
        {
            get { return _bindingSource.DataSource as DataTable; }
            set
            {
                _bindingSource.DataSource = null;
                _bindingSource.DataSource = value;
                AddNewRow();

                int billCount, doxCount, packCount;
                decimal totalRate, commission;
                OrderENT.CalculateBillCount(_bindingSource.DataSource as DataTable, out billCount, out doxCount, out packCount,
                    out totalRate, out commission);

                lblBillCount.Text = "Số bill: " + billCount;
                lblDoxCount.Text = "Số DOX: " + doxCount;
                lblPackCount.Text = "Số PACK: " + packCount;
                lblTotalRate.Text = Utility.CurrencyParse(totalRate);
                lblCommission.Text = Utility.CurrencyParse(commission);
            }
        }

        #endregion

        #region Public Methods

        public override void Save()
        {
            try
            {
                dtgOrder.EndEdit();
                dtgOrder.CurrentCell = dtgOrder[colNumber.Index, dtgOrder.CurrentCell.RowIndex];

                _presenter.Save();
                LoadData<AccountOrderENT>();
                SetMessage("Dữ liệu đã lưu thành công");
                if (dtgOrder.RowCount > 0)
                    dtgOrder.CurrentCell = dtgOrder[colCustomerName.Index, dtgOrder.RowCount - 1];
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        public override void Export()
        {
            CustomerExportView view = new CustomerExportView();
            view.From = dtpFrom.Value;
            view.To = dtpTo.Value;
            view.ShowDialog();
        }

        public override void RefreshData()
        {
            LoadCountry();
            LoadCustomer();
            LoadSale();
            LoadCarrier();
            LoadSupplier();
        }

        public void AddNewRow()
        {
            DataTable dt = this.Table;
            DataRow row = dt.NewRow();
            int rowCount = dt.Rows.Count;
            row["OrderID"] = -(rowCount + 1);
            row["Number"] = rowCount + 1;
            row["OrderDate"] = DateTime.Today;
            row["VATPercent"] = 0.1;
            dt.Rows.Add(row);
            dtgOrder.CurrentCell = dtgOrder[colCustomerName.Index, rowCount];
        }

        public void UpdateFuel()
        {
            UpdateFuelView view = new UpdateFuelView();
            if (view.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                btnSearch_Click(btnSearch, null);
        }

        #endregion
    }
}
